package com.ts.api.interceptor;

import com.gitee.apanlh.spring.BeanContextUtils;
import com.ts.api.common.context.ChannelUserContext;
import com.ts.api.module.channel.entity.cache.ChannelCacheUser;
import com.ts.api.module.channel.service.ChannelLoginService;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 渠道用户拦截器
 */
@Component
public class ChannelUserHandler implements HandlerInterceptor {

    private ChannelLoginService channelLoginService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        initBean();
        ChannelCacheUser loginUser = channelLoginService.getLoginUser();
        ChannelUserContext.USER.set(loginUser);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ChannelUserContext.USER.remove();
    }

    private void initBean() {
        if (channelLoginService == null) {
            channelLoginService = BeanContextUtils.getBean(ChannelLoginService.class);
        }
    }
}
